<template>
  <!-- ******************************************************* -->
  <!-- 查询条件区域 -->
  <!-- ******************************************************* -->
  <div style="text-align:left" v-if="false">

    <el-form :inline="true" :model="queryParm">

      <el-form-item label="上级菜单">
        <el-input v-model="queryParm.PARENT_ID" clearable />
      </el-form-item>
      <el-form-item label="菜单名称">
        <el-input v-model="queryParm.NAME" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onQuery">
          <el-icon style="margin-right: 6px;">
            <Search />
          </el-icon>
          {{ $t('common.query') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- ******************************************************* -->
  <!-- 操作按钮区域 -->
  <!-- ******************************************************* -->
  <div style="text-align:right; margin-bottom: 10px;">
    <el-button @click="onSave" type="primary">
      <el-icon style="margin-right: 6px;">
        <CirclePlus />
      </el-icon>
      保存
    </el-button>
  </div>

  <!-- ******************************************************* -->
  <!-- 数据列表区域 -->
  <!-- ******************************************************* -->
  <div class="dataArea">
    <el-table :data="tableData" height="100%" highlight-current-row @current-change="handleTableSelectRow"
      ref="multipleTableRef" @selection-change="handleSelectionChange" row-key="ID"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      style="width: 100%; font-size: 12px; border-radius: 4px; border: 1px solid #eee" :header-cell-style="{
        background: '#fafafa',
        color: '#333',
        fontWeight: '600',
        fontSize: '14px'
      }">
      <el-table-column type="selection" :reserve-selection="true" width="55" />
      <el-table-column prop="CODE" :show-overflow-tooltip="true" label="权限代码" width="120" />
      <el-table-column prop="ICON" label="菜单" width="220">
        <template #default="scope">
          <!--
            <el-icon>
                <component :is="scope.row.ICON" />
            </el-icon>
            -->
          <span style="margin-left:6px">
            {{ scope.row.NAME }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="ROUTE_TYPE" label="路由方式" width="180">
        <template #default="scope">
          {{ dictOptionsRouteTypeMap[scope.row.ROUTE_TYPE] }}
        </template>
      </el-table-column>
      <el-table-column prop="ROUTE" :show-overflow-tooltip="true" label="路由地址" />
      <el-table-column prop="STATE" label="当前状态" width="180">
        <template #default="scope">
          {{ dictOptionsStateMap[scope.row.STATE] }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
  
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { generateTreeData, findNode } from '~/util/tree'

const props = defineProps(['roleId'])

// 多选选中的行
const multipleSelection = ref([])

// 处理字典
import { loadDictList, loadDictMap } from '~/util/dict'
import { nextTick } from 'process'

// 路由方式
const dictOptionsRouteTypeMap = reactive({});
loadDictMap('SYSTEM_MENU_OPENTYPE', (mapData: []) => {
  for (let key in mapData) {
    dictOptionsRouteTypeMap[key] = mapData[key].TITLE;
  }
});

// 当前状态
const dictOptionsStateMap = reactive({});
loadDictMap('SYSTEM_MENU_STATE', (mapData: []) => {
  for (let key in mapData) {
    dictOptionsStateMap[key] = mapData[key].TITLE;
  }
});

onMounted(() => {
  onQuery();
})

// ========================================================================
// 处理列表查询相关代码
// ========================================================================
let queryParm = reactive({
  ID: '',
  PARENT_ID: '',
  NAME: '',
  ICON: '',
  IS_MENU: '',
  ROUTE_TYPE: '',
  ROUTE: '',
  STATE: '',
  SORT: '',
})

const currentPage = ref(1);  // 当前页
const pageSize = ref(500000);     // 每页记录条数
const totalRow = ref(0);     // 总行数（查询接口将返回）

const isSelectedRow = ref(false);  // 是否选择了一行数据
let currentSelectRow = reactive({});  // 当前选中行的数据[-1：未选择行]

let tableData = reactive([])
const multipleTableRef = ref<InstanceType<typeof ElTable>>()


// 查询数据
function onQuery() {
  var inParm = {
    'roleId': props.roleId,
    'current': currentPage.value,
    'size': pageSize.value,
    'isDownExcel': '0'
  };

  axios.post("/api/system/role/functions", inParm).then(res => {
    if (res.data.code == "200") {
      //请添加执行成功后的业务代码 
      if (res.data != null && res.data.success) {
        currentPage.value = res.data.data.page.current;
        pageSize.value = res.data.data.page.size;
        totalRow.value = res.data.data.page.total;

        //清空数组
        isSelectedRow.value = false;
        currentSelectRow = {};  // 清空当前选中行
        tableData.length = 0;

        var lobj_treeSourceData: [] = [];  //res.data.data.list;
        res.data.data.list.forEach(val => lobj_treeSourceData.push(Object.assign({}, val)));

        var lobj_tempData = generateTreeData(lobj_treeSourceData, 'ID', 'PARENT_ID');
        for (var i = 0; i < lobj_tempData.length; i++) {
          tableData.push(lobj_tempData[i]);
        }

        
        res.data.data.list.forEach((row:any)=>{
          if (row.AUTH_ID != null) {
          multipleTableRef.value!.toggleRowSelection(row, true);
          }
        })
        /*
        // 循环生成选中数据
        for (var i = 0; i < res.data.data.list.length; i++) {
          if (res.data.data.list[i].AUTH_ID != null) {
            var lobj_node = findNode(tableData, "ID", res.data.data.list[i].ID);
            //multipleSelection.value.push(lobj_node);
            multipleTableRef.value!.toggleRowSelection(lobj_node, true);
            console.log(lobj_node)
          }
        }*/

      }
    } else {
      // 错误消息为：res.data.msg 
      // 请添加执行失败后的业务代码 
    }
  });
}

/**
 *  选中一行
 * */
const handleTableSelectRow = (currentRow: any, oldCurrentRow: any) => {
  isSelectedRow.value = true;
  currentSelectRow = currentRow;
}


const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}

// 保存
const onSave = () => {

  // import axios from 'axios' 
  axios.post("/api/system/role/function/save",
    {
      'roleId': props.roleId,
      'functions': multipleSelection.value
    }).then(res => {
      if (res.data.code == "200") {
        //请添加执行成功后的业务代码 
      } else {
        // 错误消息为：res.data.msg 
        // 请添加执行失败后的业务代码 
      }
    });
}

</script>
  
<style>
.dataArea {
  height: calc(100vh - 280px);
}

.paginationArea {
  margin-top: 8px;
  float: right;
}
</style>
  